#coding=utf8
__author__ = 'alex'
import sys
import os
import uuid
import logging
from flask import Flask, g, session
import settings
from admin import admin
from index import index
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, scoped_session
from flask.ext.script import Manager
import biz

dir_path = os.getcwd()
if dir_path not in sys.path:
    sys.path.append(dir_path)

app = Flask("yun")
app.config.from_object(settings)
app.register_blueprint(admin)
app.register_blueprint(index)

manager = Manager(app)
DB=create_engine(settings.DB_URI,encoding = "utf-8",pool_recycle=settings.TIMEOUT,echo=False)
Session = scoped_session(sessionmaker(bind=DB))


def init_db():
    from models import Base
    Base.metadata.create_all(bind=DB)


@app.before_request
def before_request():
    """
    在请求执行前执行
    """
    g.db = Session()
    #用户登陆信息加载
    g.user_name = session.get('user_name', None)
    g.logined =True if g.user_name else False
    #管理员登陆信息加载
    if not session.get("session_id", None):
        session["session_id"] = uuid.uuid4().hex
    g.session_id = session["session_id"]

@app.after_request
def after_request(response):
    try:
        g.db.flush()
        g.db.commit()
        g.db.close()
    except Exception, e:
        logging.error(e.message)
        g.db.rollback()
    return response

@app.teardown_request
def tear_down(exception=None):
    """
    当请求结束的时候执行
    """
    try:
        if exception:
            g.db.rollback()
        else:
            g.db.commit()
        g.db.close()
    except Exception, e:
        logging.error(e.message)
        g.db.rollback()

@manager.command
def init():
    g.db = Session()
    init_db()
    g.db.commit()
    biz.init_site_data()
    print "done"
    g.db.close()

if __name__ == "__main__":
    manager.run()
